package com.jcnet.bizaia.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract.Constants;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * @package：com.example.filesavetest
 * @author：Allen
 * @email：jaylong1302@163.com
 * @data：2012-9-11 下午5:34:37
 * @funtion: 包括android中文本读写，图片压缩，图片圆角处理
 * @description：The class is for prividing a help for android apps
 */
@TargetApi(8)
public class Toolkit {

	/**
	 * 
	 * Role:Telecom service providers获取手机服务商信息 <BR>
	 * 
	 * 需要加入权限<uses-permission
	 * android:name="android.permission.READ_PHONE_STATE"/> <BR>
	 * Date:2012-3-12 <BR>
	 * 
	 * @author CODYY)allen
	 */
	public static String getProvidersName(Context context) {
		String ProvidersName = "nosim";
		try {
			// 返回唯一的用户ID;就是这张卡的编号神马的
			TelephonyManager telephonyManager = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			String IMSI = telephonyManager.getSubscriberId();
			// IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
			if (IMSI.startsWith("46000") || IMSI.startsWith("46002"))
				ProvidersName = "中国移动";
			else if (IMSI.startsWith("46001"))
				ProvidersName = "中国联通";
			else if (IMSI.startsWith("46003"))
				ProvidersName = "中国电信";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ProvidersName;
		}
		return ProvidersName;
	}

	/**
	 * 获取手机号
	 * 
	 * @param context
	 * @return
	 */
	public static String getPhone(Context context) {
		TelephonyManager phoneMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return phoneMgr.getLine1Number();
	}

	/**
	 * 获取手机型号
	 * 
	 * @return
	 */
	public static String getPhoneType() {
		return Build.MODEL;
	}

	/**
	 * 获取sdk版本
	 * 
	 * @return
	 */
	public static String getSDKVersion() {
		return Build.VERSION.SDK;
	}

	/**
	 * 获取版本号
	 * 
	 * @return
	 */
	public static String getVersion() {
		return Build.VERSION.RELEASE;
	}

	public static class TelephonyManagerInfo {
		/**
		 * 电话状态： 1.tm.CALL_STATE_IDLE=0 无活动
		 * 
		 * 2.tm.CALL_STATE_RINGING=1 响铃
		 * 
		 * 3.tm.CALL_STATE_OFFHOOK=2 摘机
		 */
		public static int CallState;
		/**
		 * 
		 * 电话方位：(需要权限：android.permission.ACCESS_COARSE_LOCATION)
		 */
		public static String CellLocation;

		/**
		 * 
		 * 唯一的设备ID：
		 * 
		 * GSM手机的 IMEI 和 CDMA手机的 MEID.
		 * 
		 * Return null if device ID is not available.
		 */
		public static String DeviceId;

		/**
		 * 
		 * 设备的软件版本号：
		 * 
		 * 例如：the IMEI/SV(software version) for GSM phones.
		 * 
		 * Return null if the software version is not available.
		 */
		public static String DeviceSoftwareVersion;

		/**
		 * 
		 * 手机号：
		 * 
		 * GSM手机的 MSISDN.
		 * 
		 * Return null if it is unavailable.
		 */
		public static String Line1Number;

		/**
		 * 
		 * 附近的电话的信息:
		 * 
		 * 类型：List<NeighboringCellInfo>
		 * 
		 * 需要权限：android.Manifest.permission#ACCESS_COARSE_UPDATES
		 */
		public static List<NeighboringCellInfo> NeighboringCellInfo;// List<NeighboringCellInfo>

		/**
		 * 
		 * 获取ISO标准的国家码，即国际长途区号。
		 * 
		 * 注意：仅当用户已在网络注册后有效。
		 * 
		 * 在CDMA网络中结果也许不可靠。
		 */
		public static String NetworkCountryIso;

		/**
		 * 
		 * MCC+MNC(mobile country code + mobile network code)
		 * 
		 * 注意：仅当用户已在网络注册时有效。
		 * 
		 * 在CDMA网络中结果也许不可靠。
		 */
		public static String NetworkOperator;

		/**
		 * 
		 * 按照字母次序的current registered operator(当前已注册的用户)的名字
		 * 
		 * 注意：仅当用户已在网络注册时有效。
		 * 
		 * 在CDMA网络中结果也许不可靠。
		 */

		public static String NetworkOperatorName;// String

		/**
		 * 当前使用的网络类型：
		 * 
		 * 例如： NETWORK_TYPE_UNKNOWN 网络类型未知 0 NETWORK_TYPE_GPRS GPRS网络 1
		 * 
		 * NETWORK_TYPE_EDGE EDGE网络 2
		 * 
		 * NETWORK_TYPE_UMTS UMTS网络 3
		 * 
		 * NETWORK_TYPE_HSDPA HSDPA网络 8
		 * 
		 * NETWORK_TYPE_HSUPA HSUPA网络 9
		 * 
		 * NETWORK_TYPE_HSPA HSPA网络 10
		 * 
		 * NETWORK_TYPE_CDMA CDMA网络,IS95A 或 IS95B. 4
		 * 
		 * NETWORK_TYPE_EVDO_0 EVDO网络, revision 0. 5
		 * 
		 * NETWORK_TYPE_EVDO_A EVDO网络, revision A. 6
		 * 
		 * NETWORK_TYPE_1xRTT 1xRTT网络 7
		 */
		public static int NetworkType;// int

		/**
		 * 
		 * 手机类型：
		 * 
		 * 例如： PHONE_TYPE_NONE 无信号
		 * 
		 * PHONE_TYPE_GSM GSM信号
		 * 
		 * PHONE_TYPE_CDMA CDMA信号
		 */

		public static int PhoneType;// int

		/**
		 * 
		 * Returns the ISO country code equivalent for the SIM provider's
		 * country code.
		 * 
		 * 获取ISO国家码，相当于提供SIM卡的国家码。
		 */
		public static String SimCountryIso;// String

		/**
		 * 
		 * Returns the MCC+MNC (mobile country code + mobile network code) of
		 * the provider of the SIM. 5 or 6 decimal digits.
		 * 
		 * 获取SIM卡提供的移动国家码和移动网络码.5或6位的十进制数字.
		 * 
		 * SIM卡的状态必须是 SIM_STATE_READY(使用getSimState()判断).
		 */
		public static String SimOperator;// String

		/**
		 * 
		 * 服务商名称：
		 * 
		 * 例如：中国移动、联通
		 * 
		 * SIM卡的状态必须是 SIM_STATE_READY(使用getSimState()判断).
		 */
		public static String SimOperatorName;// String

		/**
		 * 
		 * SIM卡的序列号：
		 * 
		 * 需要权限：READ_PHONE_STATE
		 */
		public static String SimSerialNumber;// String

		/**
		 * 
		 * SIM的状态信息：
		 * 
		 * SIM_STATE_UNKNOWN 未知状态 0
		 * 
		 * SIM_STATE_ABSENT 没插卡 1
		 * 
		 * SIM_STATE_PIN_REQUIRED 锁定状态，需要用户的PIN码解锁 2
		 * 
		 * SIM_STATE_PUK_REQUIRED 锁定状态，需要用户的PUK码解锁 3
		 * 
		 * SIM_STATE_NETWORK_LOCKED 锁定状态，需要网络的PIN码解锁 4
		 * 
		 * SIM_STATE_READY 就绪状态 5
		 */
		public static int SimState;// int

		/**
		 * 
		 * 唯一的用户ID：
		 * 
		 * 例如：IMSI(国际移动用户识别码) for a GSM phone.
		 * 
		 * 需要权限：READ_PHONE_STATE
		 */
		public static String SubscriberId;// String

		/**
		 * 
		 * 取得和语音邮件相关的标签，即为识别符
		 * 
		 * 需要权限：READ_PHONE_STATE
		 */
		public static String VoiceMailAlphaTag;// String

		/**
		 * 
		 * 获取语音邮件号码：
		 * 
		 * 需要权限：READ_PHONE_STATE
		 */
		public static String VoiceMailNumber;// String

		/**
		 * 
		 * ICC卡是否存在
		 */
		public static boolean hasIccCard;// boolean

		/**
		 * 
		 * 是否漫游:
		 * 
		 * (在GSM用途下)
		 */
		public static boolean isNetworkRoaming;
	}

	/**
	 * 获取手机唯一ID
	 * 
	 * @param context
	 * @return
	 */
	public static String getPhoneUniqueId(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	/**
	 * 获取手机信息实体
	 * 
	 * @param context
	 * @return
	 */
	public static TelephonyManagerInfo getTelephonyInfo(Context context) {
		TelephonyManagerInfo info = new TelephonyManagerInfo();
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(context.TELEPHONY_SERVICE);
		info.CallState = tm.getCallState();
		info.CellLocation = tm.getCellLocation().toString();
		info.DeviceId = tm.getDeviceId();
		info.DeviceSoftwareVersion = tm.getDeviceSoftwareVersion();
		info.hasIccCard = tm.hasIccCard();
		info.isNetworkRoaming = tm.isNetworkRoaming();
		info.Line1Number = tm.getLine1Number();
		info.NeighboringCellInfo = tm.getNeighboringCellInfo();
		info.NetworkCountryIso = tm.getNetworkCountryIso();
		info.NetworkOperator = tm.getNetworkOperator();
		info.NetworkOperatorName = tm.getNetworkOperatorName();
		info.NetworkType = tm.getNetworkType();
		info.PhoneType = tm.getPhoneType();
		info.SimCountryIso = tm.getSimCountryIso();
		info.SimOperator = tm.getSimOperator();
		info.SimOperatorName = tm.getSimOperatorName();
		info.SimSerialNumber = tm.getSimSerialNumber();
		info.SimState = tm.getSimState();
		info.SubscriberId = tm.getSubscriberId();
		info.VoiceMailAlphaTag = tm.getVoiceMailAlphaTag();
		info.VoiceMailNumber = tm.getVoiceMailNumber();
		return info;
	}

	/**
	 * 取得屏幕分辨率大小
	 * 
	 * @param context
	 *            Activity上下文
	 * @return第一个值为宽度
	 */
	public static int[] getDisplayPixes(Activity context) {
		DisplayMetrics dm = new DisplayMetrics();
		context.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return new int[] { dm.widthPixels, dm.heightPixels };
	}

	/**
	 * 取得屏幕分辨宽度和高度
	 * 
	 * @param context
	 *            Activity上下文
	 * @return第一个值为宽度
	 */
	public static int[] getDisplayWidthHeight(Activity context) {
		Display dis = context.getWindowManager().getDefaultDisplay();
		return new int[] { dis.getWidth(), dis.getHeight() };
	}

	/**
	 * 检查是否有可用的网络
	 * 
	 * @param context
	 *            上下文
	 * @return true:有网络
	 */
	public static boolean isAvaliable(Context context) {
		if (isWiFiActive(context) || isNetworkAvailable(context))
			// Toast.makeText(context, "有网络！", 300).show();
			return true;
		else
			// Toast.makeText(context, "网络不正常！", 300).show();
			return false;
	}

	/** 返回当前网速 */
	public static long getNetworkSpeed() {
		// TODO Auto-generated method stub
		ProcessBuilder cmd;
		long readBytes = 0;
		BufferedReader rd = null;
		try {
			String[] args = { "/system/bin/cat", "/proc/net/dev" };
			cmd = new ProcessBuilder(args);
			Process process = cmd.start();
			rd = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			String line;
			int linecount = 0;
			while ((line = rd.readLine()) != null) {
				linecount++;
				if (line.contains("wlan0") || line.contains("eth0")) {
					// L.E("获取流量整条字符串",line);
					String[] delim = line.split(":");
					if (delim.length >= 2) {
						String[] numbers = delim[1].trim().split(" ");// 提取数据
						readBytes = Long.parseLong(numbers[0].trim());//
						break;
					}
				}
			}
			rd.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (rd != null) {
				try {
					rd.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return readBytes;
	}

	/**
	 * 检查wifi是否可用
	 * 
	 * @param inContext
	 * @return
	 */
	public static boolean isWiFiActive(Context inContext) {
		WifiManager mWifiManager = (WifiManager) inContext
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
		if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
			System.out.println("**** WIFI is on");
			return true;
		} else {
			System.out.println("**** WIFI is off");
			return false;
		}
	}

	/**
	 * 检查手机网络(非wifi)是否有用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info == null) {
				return false;
			} else {
				if (info.isAvailable()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断是否为wifi的连接ip
	 * 
	 * @return
	 */
	public static boolean isWifiConnected(Context context) {
		int ipAddress = getWifiIpInfo(context);
		if (ipAddress > 0)
			return true;
		else
			return false;
	}

	private static int getWifiIpInfo(Context context) {
		// 获取wifi服务
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		// 判断wifi是否开启
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		// return String.valueOf(wifiInfo.getIpAddress());
		int ipAddress = wifiInfo.getIpAddress();
		return ipAddress;
	}

	/**
	 * 获取wifi ip
	 * 
	 * @return
	 */
	public static String getWifiAddress(Context context) {
		int ipAddress = getWifiIpInfo(context);
		return intToIp(ipAddress);
	}

	private static String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}

	/**
	 * 获取手机mac地址<br/>
	 * 错误返回12个0
	 */
	public static String getMacAddress(Context context) {
		// 获取mac地址：
		String macAddress = "000000000000";
		try {
			WifiManager wifiMgr = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = (null == wifiMgr ? null : wifiMgr
					.getConnectionInfo());
			if (null != info) {
				if (!TextUtils.isEmpty(info.getMacAddress()))
					macAddress = info.getMacAddress().replace(":", "");
				else
					return macAddress;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return macAddress;
		}
		return macAddress;
	}

	/**
	 * 获取手机ip(此方法在android中使用获取3G网络ip地址)
	 * 
	 * @return
	 * @throws SocketException
	 * @throws UnknownHostException
	 */
	public static String getLocalIpAddress() throws SocketException {
		for (Enumeration<NetworkInterface> en = NetworkInterface
				.getNetworkInterfaces(); en.hasMoreElements();) {
			NetworkInterface intf = en.nextElement();
			for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
					.hasMoreElements();) {
				InetAddress inetAddress = enumIpAddr.nextElement();
				if (!inetAddress.isLoopbackAddress()) {
					return inetAddress.getHostAddress().toString();
				}
			}
		}
		return null;
	}

	/**
	 * 获取本机ip(此方法仅在java程序中)
	 * 
	 * @return
	 * @throws UnknownHostException
	 */
	public static String getHostAddress() throws UnknownHostException {
		InetAddress address = null;
		address = InetAddress.getLocalHost();
		return address.getHostAddress();
	}

	/**
	 * 读取文本，一次读取多个字节，默认为1024
	 * 
	 * @param file
	 *            文件名称(在sd卡下面的data/data/应用程序包下面)
	 * @param context
	 *            上下文
	 * @param encode
	 *            编码方式
	 * @return
	 * @throws IOException
	 */
	public static String readFromFileByChar(String file, Context context,
			String encode) throws IOException {
		FileInputStream fis = context.openFileInput(file);
		BufferedReader br = new BufferedReader(new InputStreamReader(fis,
				encode));
		// Log.i(TAG, br.readLine());
		int index = 0;
		char[] buffer = new char[1024];// 一次性读取1024个字符
		StringBuffer sb = new StringBuffer();
		while ((index = br.read(buffer)) != -1) {// 一次读多个字符
			// 同样屏蔽掉r不显示
			if ((index == buffer.length) && (buffer[buffer.length - 1] != 'r')) {
				sb.append(buffer);
			} else {
				for (int i = 0; i < index; i++) {
					if (buffer[i] == 'r') {
						continue;// 停止执行当前的迭代,然后退回循环开始处
					} else {
						sb.append(buffer[i]);
					}
				}
			}
		}
		br.close();
		fis.close();
		return sb.toString();
		// return br.readLine();
	}

	/**
	 * 按行读取文本
	 * 
	 * @param file
	 *            文件名
	 * @param context
	 *            上下文
	 * @param encode
	 *            编码方式
	 * @return
	 * @throws IOException
	 */
	public static String readFromFileByLine(String file, Context context,
			String encode) throws IOException {
		FileInputStream fis = context.openFileInput(file);
		BufferedReader br = new BufferedReader(new InputStreamReader(fis,
				encode));
		// Log.i(TAG, br.readLine());
		StringBuffer sb = new StringBuffer();
		String temp;
		while ((temp = br.readLine()) != null) {// 一次读一行
			sb.append(temp);
		}
		br.close();
		fis.close();
		return sb.toString();
		// return br.readLine();
	}

	/**
	 * 一次将string内容写入到文件
	 * 
	 * @param context
	 *            上下文
	 * @param file
	 *            文件名
	 * @param content
	 *            写入的内容
	 * @throws IOException
	 */
	public static void writeToFile(Context context, String file, String content)
			throws IOException {
		FileOutputStream fos = context.openFileOutput(file,
				context.MODE_PRIVATE);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
		bw.write(content);
		bw.flush();
		bw.close();
		fos.close();
	}

	/**
	 * 将object序列化到filename文件中
	 * 
	 * @param fileName
	 *            文件名,包括路径
	 * @param object
	 *            序列化的对象
	 */
	public static boolean writeFileByObject(String fileName, Object object) {
		try {
			FileOutputStream fos = new FileOutputStream(fileName);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
			oos.flush();
			oos.close();
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 反序列化
	 * 
	 * @param fileName
	 *            文件名,包括详细路径
	 * @return Object类型的对象
	 */
	public static Object readFileByObject(String fileName) {
		try {
			FileInputStream fis = new FileInputStream(fileName);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Object o = ois.readObject();
			ois.close();
			fis.close();
			return o;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 按照指定的宽度和高度压缩图片(这是android 2.2以上才有的方法)
	 * 
	 * @param bm
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap compressBitmap(Bitmap bm, int w, int h) {
		return ThumbnailUtils.extractThumbnail(bm, w, h);
	}

	/**
	 * 等比例压缩图片
	 * 
	 * @param is
	 *            图片输入流
	 * @param scalePix
	 *            压缩的尺寸
	 * @return
	 */
	public static Bitmap compressBitmapByscale(InputStream is, int scalePix) {
		BitmapFactory.Options opt = new Options();
		opt.inSampleSize = scalePix;
		return BitmapFactory.decodeStream(is, null, opt);
	}

	/**
	 * 等比例压缩图片
	 * 
	 * @param data
	 *            byte[]数组
	 * 
	 * @param ratio
	 *            压缩的尺寸
	 * @return
	 */
	public static Bitmap compressBitmap(byte[] data, int ratio) {
		BitmapFactory.Options opts = new Options();
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = ratio;
		// 得到新的图片
		return BitmapFactory.decodeByteArray(data, 0, data.length, opts);

	}

	/**
	 * 自动压缩图片(根据能够压缩的比例)
	 * 
	 * @param map
	 * @return
	 */
	public static Bitmap compressBitmapAuto(Bitmap map, int scalePix) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] data = os.toByteArray();
		opts.inJustDecodeBounds = true;
		map.compress(CompressFormat.PNG, 100, os);
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
		opts.inJustDecodeBounds = false;
		int be = (int) (opts.outHeight / (float) scalePix);
		if (be <= 0)
			be = 1;
		opts.inSampleSize = be;
		bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		return bitmap;
	}

	/** 根据屏幕大小适屏压缩 --2012/11/13-- */
	public static Bitmap compressBitmapFixDisplay(Activity context, byte[] data) {
		BitmapFactory.Options opts = new Options();
		opts.inJustDecodeBounds = true;// 设置查看图片的大小，不分配内存
		BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		int height = context.getWindowManager().getDefaultDisplay().getHeight();// 获取屏幕大小
		int width = context.getWindowManager().getDefaultDisplay().getWidth();
		int hratio = (int) Math.ceil(opts.outHeight / (float) height);// 图片的高度比上屏幕的高度
		int wratio = (int) Math.ceil(opts.outWidth / (float) width);
		if (hratio > 1 || wratio > 1) {// 如果图片超出屏幕范围
			if (hratio > wratio)// 如果高度大于宽度
				opts.inSampleSize = hratio;
			else
				opts.inSampleSize = wratio;
		}
		opts.inJustDecodeBounds = false;// 设置分配图片的大小
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
				opts);
		return bitmap;
	}

	/**
	 * 压缩图片
	 * 
	 * @param bm
	 *            所要转换的bitmap
	 * @param newWidth新的宽
	 * @param newHeight新的高
	 * @return 指定宽高的bitmap
	 */
	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		if (!bm.isRecycled())// 回收bitmap
			bm.recycle();
		return newbm;
	}

	/**
	 * 动态设置ImageView的布局宽度和高度
	 * 
	 * @param iv
	 *            ImageView对象
	 * @param width
	 *            要设置的宽度(0:充满父容器)
	 * @param height
	 *            要设置的高度(0:充满父容器)
	 */
	public static void setImagePixes(ImageView iv, int width, int height) {
		ViewGroup.LayoutParams params = iv.getLayoutParams();
		if (width == 0 && height != 0)// 如果宽度为0
		{
			params.height = height;
			params.width = ViewGroup.LayoutParams.FILL_PARENT;
		} else if (height == 0 && width != 0) {// 高度为 0
			params.height = ViewGroup.LayoutParams.FILL_PARENT;
			params.width = width;
		} else if (width == 0 && height == 0) {
			params.height = ViewGroup.LayoutParams.FILL_PARENT;
			params.width = ViewGroup.LayoutParams.FILL_PARENT;
		} else {
			params.height = height;
			params.width = width;
		}
		iv.setLayoutParams(params);
	}

	/** activity转换为view */
	@SuppressWarnings("deprecation")
	public static View activityToView(Context parent, Intent intent) {
		LocalActivityManager mLocalActivityManager = new LocalActivityManager(
				(Activity) parent, true);
		final Window w = mLocalActivityManager.startActivity("TagName", intent);
		final View wd = w != null ? w.getDecorView() : null;
		if (wd != null) {
			wd.setVisibility(View.VISIBLE);
			wd.setFocusableInTouchMode(true);
			((ViewGroup) wd)
					.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
		}
		return wd;
	}

	/***
	 * 动态设置listview的高度
	 * 
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// params.height += 5;// if without this statement,the listview will be
		// a
		// little short
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	/**
	 * 将Drawable转化为Bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
				.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;
	}

	/**
	 * 将图片的四角圆化
	 * 
	 * @param bitmap
	 * @param radius
	 *            圆角弧度，数值越大弧度越大
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int radius) {

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		// 得到画布
		Canvas canvas = new Canvas(output);

		// 将画布的四角圆化
		final int color = Color.RED;
		final Paint paint = new Paint();
		// 得到与图像相同大小的区域 由构造的四个值决定区域的位置以及大小
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		// 值越大角度越明显
		final float roundPx = radius;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		// drawRoundRect的第2,3个参数一样则画的是正圆的一角，如果数值不同则是椭圆的一角
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); // 设置形式为背景
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	/**
	 * 获得带倒影的图片方法
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
		final int reflectionGap = 4;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);
		Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
				width, height / 2, matrix, false);
		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmapWithReflection);
		canvas.drawBitmap(bitmap, 0, 0, null);
		Paint deafalutPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
				bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
				0x00ffffff, TileMode.CLAMP);
		paint.setShader(shader);// 设置阴影
		// Set the Transfer mode to be porter duff and destination in
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// Draw a rectangle using the paint with our linear gradient
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);
		return bitmapWithReflection;
	}

	/**
	 * 向preferences写入数据
	 * 
	 * @param context
	 *            上下文
	 * @param key
	 *            键
	 * @param value
	 *            写入的内容
	 */
	public static void writeToPreferences(Context context, String filename,
			String key, String value) {
		// 得到preferences对象
		SharedPreferences.Editor editor = context.getSharedPreferences(
				filename, android.content.Context.MODE_PRIVATE).edit();
		// editor = preferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

	/**
	 * 向preference中读取数据 data/data/package/shared_prefs
	 * 
	 * @param context
	 *            上下文
	 * @param filename
	 *            文件名
	 * @param key
	 *            键
	 * @param defaultValue
	 *            默认值
	 * @return
	 */
	public static String readFromPreferences(Context context, String filename,
			String key, String defaultValue) {
		// 得到preferences对象
		SharedPreferences preferences = context.getSharedPreferences(filename,
				android.content.Context.MODE_PRIVATE
						| android.content.Context.MODE_APPEND);
		return preferences.getString(key, defaultValue);
	}

	/**
	 * 加载properties文件
	 * 
	 * @param context
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static Properties loadProperties(Context context, String file,
			String encode) throws Exception {
		Properties properties = new Properties();
		FileInputStream s = new FileInputStream(file);
		properties.load(s);
		return properties;
	}

	/**
	 * 保存到properties文件中
	 * 
	 * @param context
	 * @param file
	 * @param properties
	 * @throws Exception
	 */
	public static void saveProperties(Context context, String file,
			String encode, Properties properties) throws Exception {
		FileOutputStream s = new FileOutputStream(file, false);
		properties.store(s, "");
	}

	// ---------------------------------------------------------------------------------------------------

	/**
	 * 从网络上下载
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static Bitmap getBitMapFromUrl(String url) throws IOException {
		Bitmap bitmap = null;
		URL u = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		u = new URL(url);
		conn = (HttpURLConnection) u.openConnection();
		is = conn.getInputStream();
		bitmap = BitmapFactory.decodeStream(is);
		return bitmap;
	}

	/**
	 * 异步加载网络图片
	 * 
	 * @param src图片路径
	 * @param iv
	 *            imageview
	 * @param callback回调接口
	 */
	public static void loadImage(final String src, final ImageView iv,
			final ImageCallBack callback) {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				callback.setImageBitmap((Bitmap) msg.obj, iv, src);
			}
		};
		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap bitmap = null;
				try {
					bitmap = getBitMapFromUrl(src);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (bitmap != null) {
					Message msg = handler.obtainMessage(0, bitmap);
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	/**
	 * 获取网络byte流的图片
	 * 
	 * @param src
	 * @return
	 * @throws Exception
	 */
	public static byte[] getImageBytes(String src) throws Exception {
		URL url = new URL(src);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);// 设置延迟时间为5s
		InputStream is = conn.getInputStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		while ((len = is.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		return bos.toByteArray();
	}

	/**
	 * 压缩图片
	 * 
	 * @param bm
	 *            所要转换的bitmap
	 * @param newWidth新的宽
	 * @param newHeight新的高
	 * @return 指定宽高的bitmap
	 */
	public static Bitmap zoomBitmap(byte[] data, int newWidth, int newHeight) {
		BitmapFactory.Options opts = new Options();
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = 10;
		// 得到新的图片
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
				opts);
		// 获得图片的宽高
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
				true);
		if (!bitmap.isRecycled())// 回收bitmap
			bitmap.recycle();
		return newbm;
	}

	/**
	 * 异步加载网络图片
	 * 
	 * @param src
	 *            url地址
	 * @param iv
	 *            传入的iamgeView
	 * @param callback
	 *            回调函数
	 */
	public static void AsycloadImage(final String src, final ImageView iv,
			final ImageCallBack callback) {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				callback.setImageBitmap((Bitmap) msg.obj, iv, src);
			}
		};
		new Thread(new Runnable() {
			@Override
			public void run() {
				byte[] data = null;
				Bitmap bitmap = null;
				try {
					data = getImageBytes(src);
					bitmap = compressBitmap(data, 3);

				} catch (Exception e) {
					e.printStackTrace();
				}
				if (bitmap != null) {
					Message msg = handler.obtainMessage(0, bitmap);
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	/**
	 * 异步加载图片
	 * 
	 * @param url
	 *            图片路径
	 * @param iv
	 *            ImageView
	 * @param imgCache
	 *            缓存
	 * @param callback
	 *            回调接口
	 */
	public static void AyncLoadImageFromUrl(final String url,
			final ImageView iv,
			final Map<String, SoftReference<Bitmap>> imgCache,
			final ImageCallBack callback) {
		if (imgCache.containsKey(url))// 如果缓存中存在
		{
			iv.setImageBitmap(imgCache.get(url).get());
			return;
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				callback.setImageBitmap((Bitmap) msg.obj, iv, url);
			}
		};
		new Thread(new Runnable() {

			@Override
			public void run() {
				byte[] data = null;
				Bitmap bitmap = null;
				try {
					data = getImageBytes(url);
					bitmap = compressBitmap(data, 3);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (bitmap != null) {
					// 保存到缓存中
					// 将图片保存到缓存中
					imgCache.put(url, new SoftReference<Bitmap>(bitmap));
					Message msg = handler.obtainMessage(0, bitmap);
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	/**
	 * 保存图片到sdcard，并且返回图片名称，带后缀名
	 * 
	 * @param context
	 * @param fileName
	 *            图片目录名称
	 * @param photo
	 *            图片路径
	 * @throws IOException
	 */
	public static String saveImgToSdcard(Context context, String fileName,
			String photo) throws IOException {
		String url = photo;
		// 获取图片名称,包含后缀
		String imgName = url.substring(url.lastIndexOf("/") + 1, url.length());
		URL Url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
		InputStream is = conn.getInputStream();
		String saveUrl = context.getFilesDir() + "/" + fileName + "/" + imgName;
		File file = new File(saveUrl);
		// 如果图片文件存在
		if (file.exists())
			return imgName;
		FileOutputStream fos = new FileOutputStream(file);
		byte[] data = new byte[512];
		int len = 0;
		while ((len = is.read(data)) != -1) {
			fos.write(data, 0, len);
		}
		fos.flush();
		fos.close();
		return imgName;
	}

	/**
	 * 保存图片到指定的目录
	 * 
	 * @param context
	 *            上下文
	 * @param filedir
	 *            图片目录名称
	 * @param name
	 *            图片名称
	 * @param bitmap
	 *            图片
	 * @throws Exception
	 */
	public static void saveBitmapToSdcard(Context context, String filedir,
			String name, Bitmap bitmap) throws Exception {
		String path = context.getFilesDir() + File.separator + filedir
				+ File.separator;
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		file = new File(path + name + ".png");
		if (file.exists())
			return;
		FileOutputStream fos = new FileOutputStream(file);
		bitmap.compress(CompressFormat.PNG, 100, fos);
		fos.close();
	}

	/** 从sdcard制定目录读取图片 */
	public static Bitmap getBitmapFromSdcard(Context context, String file,
			String name) {
		String src = context.getFilesDir() + "/" + file + "/" + name;
		Bitmap bitmap = BitmapFactory.decodeFile(src);
		return bitmap;
	}

	/**
	 * 从缓存中读取
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Bitmap getImgFromCache(final String url, final ImageView iv,
			final Map<String, SoftReference<Bitmap>> imgCache,
			final ImageCallBack callback) throws Exception {
		// 从内存中读取
		if (imgCache.containsKey(url)) {
			synchronized (imgCache) {
				SoftReference<Bitmap> bitmapReference = imgCache.get(url);
				if (null != bitmapReference) {
					return bitmapReference.get();
				}
			}
		}
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				callback.setImageBitmap((Bitmap) msg.obj, iv, url);
			}
		};
		// 從網絡中下載
		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap bitmap = null;
				try {
					bitmap = getBitMapFromUrl(url);
				} catch (IOException e) {
					e.printStackTrace();
				}
				// 将图片保存进内存中
				imgCache.put(url, new SoftReference<Bitmap>(bitmap));
				Message msg = handler.obtainMessage(0, bitmap);
				handler.sendMessage(msg);
			}
		}).start();
		return null;
	}

	public interface ImageCallBack {
		public void setImageBitmap(Bitmap bitmap, ImageView iv, String url);
	}

	/**
	 * get 请求
	 * 
	 * @param url路径
	 * @return
	 * @throws Exception
	 * @throws ClientProtocolException
	 */
	public static HttpResponse get(String url) throws Exception {
		HttpResponse response = null;
		HttpClient client = new DefaultHttpClient();
		// 设置连接超时
		client.getParams().setIntParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
		// 设置编码
		// client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
		// "gb2312");
		// get方式
		HttpGet httpRequest = new HttpGet(url);
		// 发出一个request,并返回一个基于http协议的response
		// System.out.println("------toolkit 1066----------");
		response = client.execute(httpRequest);
		return response;
	}

	/**
	 * post请求
	 * 
	 * @param path
	 *            请求的地址
	 * @param params
	 *            参数列表
	 * @return
	 * @throws Exception
	 */
	public static InputStream postRequest(String path,
			Map<String, String> params) throws Exception {
		// 封装请求参数
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				pair.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
			}
		}
		// 把请求参数变成请求体部分
		UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");		
		
		
		// 使用HttpPost对象设置发送的URL路径
		final HttpPost post = new HttpPost(path);
		// 发送请求体
		post.setEntity(uee);
		// 创建一个浏览器对象，以把POST对象向服务器发送，并返回响应消息
		DefaultHttpClient dhc = new DefaultHttpClient();
		// 设置连接超时
		dhc.getParams().setIntParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
		dhc.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000); // 设置等待数据超时10s
		HttpResponse response = dhc.execute(post);
		Log.e("TAG", "服务器返回状态：----" + response.getStatusLine().getStatusCode());
		if (response != null && response.getStatusLine().getStatusCode() == 200) {
			return response.getEntity().getContent();
		} else
			post.abort();
		return null;
	}

	/**
	 * post请求
	 * 
	 * @param url路径
	 * @param list
	 *            参数列表
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static HttpResponse post(String url, List<BasicNameValuePair> list,
			String encode) throws Throwable {
		HttpResponse response = null;
		HttpClient client = new DefaultHttpClient();
		// 设置连接超时
		client.getParams().setIntParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
		client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
				5000); // 设置等待数据超时5s
		// 创建一个 基于http协议的请求(post方式)
		HttpPost httpRequest = new HttpPost(url);
		if (list != null) {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
			// 将请求中的参数信息放置到request中
			httpRequest.setEntity(entity);
		}
		// 发出一个request,并返回一个基于http协议的response
		response = client.execute(httpRequest);
		return response;

	}

	/*
	 * 参数说明: uploadUrl: Servlet的url fileName: 上传图片的文件名(如: qq.png) fileUrl:
	 * 上传文件在手机客户端的完整路径(如: /sdcard/qq.png)
	 */
	public static InputStream upload(String uploadUrl, String fileName,
			String fileUrl) throws Exception {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		InputStream is = null;
		URL url = new URL(uploadUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		/* 允许Input、Output，不使用Cache */
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		/* 设置传送的method=POST */
		conn.setRequestMethod("POST");
		/* setRequestProperty */
		conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="
				+ boundary);
		// 将phone放置到请求的头部

		if (fileName != null && fileUrl != null) {
			conn.setRequestProperty("picName", fileName);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + fileName + "\"" + end);
			ds.writeBytes(end);

			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(fileUrl);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

			/* close streams */
			fStream.close();
			ds.flush();
			ds.close();
		}
		/* 取得Response内容 */
		is = conn.getInputStream();
		return is;
	}

	// -------------------------------------加密，验证，转换系列-----------------------------------------------------------
	/**
	 * 验证是否为手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		// Pattern p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,2,5-9]))\\d{8}$");
		Pattern p = Pattern.compile("^([0-9]{3})\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 验证输入是否为邮箱
	 * 
	 * @param strEmail
	 * @return
	 */
	public static boolean isEmail(String strEmail) {
		 boolean tag = true;
	        final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	        final Pattern pattern = Pattern.compile(pattern1);
	        final Matcher mat = pattern.matcher(strEmail);
	        if (!mat.find()) {
	            tag = false;
	        }
	        return tag;
	}

	/**
	 * 验证输入是否6位数字
	 * 
	 * @param strEmail
	 * @return
	 */
	public static boolean isCode(String strCode) {
		String strPattern = "^[0-9]{6}";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strCode);
		return m.matches();
	}

	/**
	 * 验证输入是否6位字符包含数字和字母，不包含特殊字符
	 * 
	 * @param strEmail
	 * @return
	 */
	public static boolean isCheckCode(String strCode) {
		String strPattern = "^[0-9a-zA-Z]{6}";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strCode);
		return m.matches();
	}

	/**
	 * 验证输入是否6到12位上字符包含数字和字母，包含特殊字符
	 * 
	 * @param strEmail
	 * @return
	 */
	public static boolean isPassCode(String strCode) {
		String strPattern = "^[0-9a-zA-Z@*%#()><!_~]{6,12}";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strCode);
		return m.matches();
	}

	/**
	 * 过滤url
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isLegalUrlParameters(String str) {
		String strPattern = "[&=\\s]+";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(str);
		return m.find();
	}

	/**
	 * 验证ip
	 * 
	 * @param text
	 * @return
	 */
	public static boolean isIp(String text) {
		if (text != null && text != "") {
			// 定义正则表达式
			String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
			// 判断ip地址是否与正则表达式匹配
			if (text.matches(regex)) {
				// 返回判断信息
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	/**
	 * md5加密
	 * 
	 * @param s
	 * @return
	 * @throws Exception
	 */
	public final static String MD5(String s) throws Exception {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };

		byte[] strTemp = s.getBytes();
		MessageDigest mdTemp = MessageDigest.getInstance("MD5");
		mdTemp.update(strTemp);
		byte[] md = mdTemp.digest();
		int j = md.length;
		char str[] = new char[j * 2];
		int k = 0;
		for (int i = 0; i < j; i++) {
			byte byte0 = md[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(str);
	}

	/**
	 * 加密
	 * 
	 * @param sSrc
	 *            原文
	 * @param sKey
	 *            密码是16位
	 * @return
	 * @throws Exception
	 */
	public static String AESEncrypt(String sSrc, String sKey) throws Exception {
		if (sKey == null) {
			System.out.print("Key为空null");
			return null;
		}
		// 判断Key是否为16位
		if (sKey.length() != 16) {
			System.out.print("Key无效");
			return null;
		}
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes());
		return byte2hex(encrypted).toLowerCase();
	}

	/**
	 * 解密
	 * 
	 * @param sSrc
	 * @param sKey密码是16位
	 * @return
	 * @throws Exception
	 */
	public static String AESDecrypt(String sSrc, String sKey) throws Exception {
		// 判断Key是否正确
		if (sKey == null) {
			System.out.print("Key为空null");
			return null;
		}
		// 判断Key是否为16位
		if (sKey.length() != 16) {
			System.out.print("Key无效");
			return null;
		}
		byte[] raw = sKey.getBytes("ASCII");
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
		byte[] encrypted1 = hex2byte(sSrc);
		byte[] original = cipher.doFinal(encrypted1);
		String originalString = new String(original);
		return originalString;
	}

	private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1',
			(byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
			(byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B',
			(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' };

	/**
	 * 十六进制无符号整数形式
	 * 
	 * @param raw
	 * @param len
	 * @return
	 */
	public static String getHex(byte[] raw, int len) {
		byte[] hex = new byte[2 * len];
		int index = 0;
		int pos = 0;

		for (byte b : raw) {
			if (pos >= len)
				break;

			pos++;
			int v = b & 0xFF;
			hex[index++] = HEX_CHAR_TABLE[v >>> 4];
			hex[index++] = HEX_CHAR_TABLE[v & 0xF];
		}
		return new String(hex);
	}

	/**
	 * 转换为10进制无符号字符串
	 * 
	 * @param bytes
	 * @return
	 */
	public static long getDec(byte[] bytes) {
		long result = 0;
		long factor = 1;
		for (int i = 0; i < bytes.length; ++i) {
			long value = bytes[i] & 0xffl;
			result += value * factor;
			factor *= 256l;
		}
		return result;
	}

	/**
	 * 二进制转换为16进制
	 * 
	 * @param b
	 * @return
	 */
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}

	/**
	 * 16进制转换为二进制
	 * 
	 * @param strhex
	 * @return
	 */
	public static byte[] hex2byte(String strhex) {
		if (strhex == null) {
			return null;
		}
		int l = strhex.length();
		if (l % 2 == 1) {
			return null;
		}
		byte[] b = new byte[l / 2];
		for (int i = 0; i != l / 2; i++) {
			b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
					16);
		}
		return b;
	}

	/**
	 * 16进制字符转换为int
	 * 
	 * @param c
	 * @return
	 */
	public static int reverseToInt(char c) {
		if (c == 'A')
			return 10;
		else if (c == 'B')
			return 11;
		else if (c == 'C')
			return 12;
		else if (c == 'D')
			return 13;
		else if (c == 'E')
			return 14;
		else if (c == 'F')
			return 15;
		else
			return Integer.parseInt(String.valueOf(c));
	}

	/**
	 * 16进制加法
	 * 
	 * @param src1
	 * @param src2
	 * @return
	 */
	public static String hexAdd(String src1, String src2) {
		int length1 = src1.toUpperCase().length();
		int length2 = src2.toUpperCase().length();
		String extend = "";
		char sum[] = null;
		if (length1 > length2) {// 如果src1的长度大于src2
			int num = length1 - length2;
			sum = new char[length1];
			String zero = "";
			for (int i = 0; i < num; i++) {
				zero += "0";
			}
			src2 = zero + src2;
			// 遍历数组，然后相加
			int add = 0, rest = 0;
			for (int i = length1 - 1; i >= 0; i--) {
				int a = reverseToInt(src1.toUpperCase().charAt(i));
				int b = reverseToInt(src2.toUpperCase().charAt(i));
				if (a + b + add >= 16) {
					int temp = add;
					add = (a + b + add) / 16;
					rest = (a + b + temp) % 16;
					sum[i] = reverseToChar(rest);
				} else {
					sum[i] = reverseToChar(a + b + add);
					add = 0;
				}
			}
		} else if (length1 < length2) {// src1的长度小于src2
			int num = length2 - length1;
			sum = new char[length2];
			String zero = "";
			for (int i = 0; i < num; i++) {
				zero += "0";
			}
			src1 = zero + src1;
			// 遍历数组，然后相加
			int add = 0, rest = 0;
			for (int i = length2 - 1; i >= 0; i--) {
				int a = reverseToInt(src1.toUpperCase().charAt(i));
				int b = reverseToInt(src2.toUpperCase().charAt(i));
				if (a + b + add >= 16) {
					int temp = add;
					add = (a + b + add) / 16;
					rest = (a + b + temp) % 16;
					sum[i] = reverseToChar(rest);
				} else {
					sum[i] = reverseToChar(a + b + add);
					add = 0;
				}
			}
		} else {// 如果相等
			// 遍历数组，然后相加
			sum = new char[length2];
			int add = 0, rest = 0;
			for (int i = length2 - 1; i >= 0; i--) {
				int a = reverseToInt(src1.toUpperCase().charAt(i));
				int b = reverseToInt(src2.toUpperCase().charAt(i));
				if (a + b + add >= 16) {
					int temp = add;
					add = (a + b + add) / 16;
					rest = (a + b + temp) % 16;
					sum[i] = reverseToChar(rest);
					if (i == 0) {// 如果i==0
						extend = String.valueOf(add);
					}
				} else {
					sum[i] = reverseToChar(a + b + add);
					add = 0;
				}
			}
		}
		return extend + String.valueOf(sum);
	}

	/**
	 * 整形转为16进制表示的char
	 * 
	 * @param num
	 * @return
	 */
	public static char reverseToChar(int num) {
		/*
		 * if (num == 10) return 'A'; else if (num == 11) return 'B'; else if
		 * (num == 12) return 'C'; else if (num == 13) return 'D'; else if (num
		 * == 14) return 'E'; else if (num == 15) return 'F'; else return
		 * String.valueOf(num).charAt(0);
		 */
		return Integer.toHexString(num).charAt(0);
	}

	/**
	 * 16进制字符按位取反
	 * 
	 * @param num
	 * @return
	 */
	public static String revers(String num) {
		num = num.toUpperCase();
		char array[] = num.toCharArray();
		for (int i = 0; i < array.length; i++) {
			if (array[i] == 'A')
				array[i] = reverseToChar(15 - 10);
			else if (array[i] == 'B')
				array[i] = reverseToChar(15 - 11);
			else if (array[i] == 'C')
				array[i] = reverseToChar(15 - 12);
			else if (array[i] == 'D')
				array[i] = reverseToChar(15 - 13);
			else if (array[i] == 'E')
				array[i] = reverseToChar(15 - 14);
			else if (array[i] == 'F')
				array[i] = reverseToChar(15 - 15);
			else
				array[i] = reverseToChar(15 - Integer.parseInt(String
						.valueOf(array[i])));
		}
		//
		return String.valueOf(array);
	}

	/**
	 * 输入流转换为byte数组
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] streamToBytes(InputStream is) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = is.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
		return os.toByteArray();
	}

	/**
	 * 将输入流转为字符串
	 * 
	 * @param is
	 *            输入流
	 * @param encode
	 *            编码方式
	 * @return
	 * @throws Exception
	 */
	public static String streamToString(InputStream is, String encode)
			throws Exception {
		byte[] data = streamToBytes(is);
		return new String(data, encode);
	}

	/**
	 * 将String转换成InputStream
	 * 
	 * @param in
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	public static InputStream StringTOInputStream(String in, String encode)
			throws IOException {
		ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes(encode));
		return is;
	}

	/**
	 * 将byte数组转换为输入流
	 * 
	 * @param data
	 * @return
	 */
	public static InputStream ByteToStream(byte[] data) {
		ByteArrayInputStream os = new ByteArrayInputStream(data);
		return os;
	}

	/**
	 * 资源文件转换为bitmap
	 * 
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap getBitmapFromResource(Context context, int resId) {
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is);
	}

	/**
	 * 返回当前日期xxxx年x月xx日x星期
	 * 
	 * @return
	 */
	public static String getDate() {
		Date date = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		int w = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		String mDate = c.get(Calendar.YEAR) + "年" + c.get(Calendar.MONTH) + "月"
				+ c.get(Calendar.DATE) + "日  " + weekDays[w];
		return mDate;
	}
}
